package o2o.web.actions.notify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jinyou.utils.common.AjaxResult;
import lombok.Data;
import lombok.experimental.Accessors;
import o2o.config.dao.UserDaoSql;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Jahnke【1029777564@qq.com】
 * @ClassName DistributeCommiosionNotify
 * @Description:
 * @date 2020/11/23 11:44
 * @Version 1.0
 */
@RestController
public class DistributeCommiosionNotifyController {

    // 更新订单分享佣金总额
    @RequestMapping(method = RequestMethod.POST, value = "\"notify/commision/update")
    public String commisionNotify(String json) {
        // ALTER TABLE order_pay ADD COLUMN disCommisionMoney DECIMAL(8,2) DEFAULT 0 COMMENT '分销佣金总额';
        // 格式化代码
        List<OrderCommisionTO> list = JSONArray.parseArray(json, OrderCommisionTO.class);
        if (list != null) {
            /**
             * UPDATE order_pay SET disCommisionMoney=(
             * 	CASE
             * 	WHEN orderno='2008070857420001' THEN 1
             * 	WHEN orderno='2008070900530002' THEN 2
             * 	END
             * ) WHERE orderno IN('2008070857420001','2008070900530002')
             */
            StringBuilder sql = new StringBuilder("UPDATE order_pay \n")
                    .append("SET disCommisionMoney=( \n")
                    .append("   CASE \n");
            for (int i = 0; i < list.size(); i++) {
                sql.append("    WHEN orderno='" + list.get(i).getOrderNo() + " ' THEN ").append(list.get(i).getCommisionMoney()).append(" \n");
            }
            sql.append("    END \n");
            sql.append(") WHERE orderno IN('" + (StringUtils.join(list.stream().map(a -> a.getOrderNo()).collect(Collectors.toList()), "','")) + "')\n");
            try {
                UserDaoSql.getInstance().executeBySql(sql.toString());
            } catch (SQLException e) {
                System.out.println(sql.toString());
                e.printStackTrace();
                return AjaxResult.errorResult(e.getMessage());
            }
        }
        return AjaxResult.successResult();
    }

    public static void main(String[] args) {
        String json = "[{\"sysCustomer\":\"oxo-xlc\",\"orderNo\":\"123456\",\"commisionMoney\":12.23}]";

        List<OrderCommisionTO> list = JSONArray.parseArray(json, OrderCommisionTO.class);
        System.out.println(JSON.toJSONString(list));
    }
}

@Data
@Accessors(chain = true)
class OrderCommisionTO {
    private String sysCustomer;
    private String orderNo;
    private Double commisionMoney;
}
